//
//  EyuSDKBridge.m
//  QySDKBridge
//
//  Created by lcc on 2025/2/10.
//

#import "EyuSDKBridge.h"
#import <EyuGameSDK/AboGameSDKApi.h>
#import <QySDKBridge/SDKBridgeUtil.h>
#import <QySDKBridge/QyBaseEvent.h>
#import <QySDKBridge/EyuPurchaseBridge.h>
#import "SDKBridgeConstant.h"
#import "EyuReportBridge.h"
#import "EyuHeader.h"
#import "EyuAdBridge.h"
static EyuSDKBridge*object=nil;
@interface EyuSDKBridge()
@property(nonatomic,strong)NSString *m_InitResult;
@property(nonatomic,strong)NSString *m_LoginResult;
@property(nonatomic,assign)BOOL m_IsLoginSucceed;
@end
@implementation EyuSDKBridge

+(instancetype)Instance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        object=[[EyuSDKBridge alloc]init];
    });
    return object;
}

-(instancetype)init{
    if (self=[super init]) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(UserSignOtherAccount:) name:@"kGameForUserSignInOtherAccountKey" object:nil];
    }
    return self;
}

-(void)initServer:(UIApplication *)application options:(NSDictionary *)options{
    //预先初始化一下查询价格所需的容器
    NSLog(@"EyuSDKBridge - initServer...");
    [EyuHeader Instance].m_ProductPriceDict=[NSMutableDictionary dictionary];
    [[AboGameSDKApi SDKManager]StartSDKServiceWithOwnApplication:application options:options language:nil];
}


// 初始化SDK
- (void)initSDK{
    NSLog(@"EyuSDKBridge - InitSDK...");
    [[AboGameSDKApi SDKManager]GameSDKServiceInitEyuSuccess:^(NSDictionary * _Nonnull successBack) {
        NSLog(@"EyuSDKBridge - Init Success! - msg:%@", successBack);
        NSString * callMsg = [SDKBridgeUtil ObjectToJson:successBack];
        self.m_InitResult = @"1!state:success";
        [SDKBridgeUtil SendMsgToUnity:UnitySdkInitSuccessFunc msg:callMsg];
        //登录
        [self login];
    } eyuFail:^(NSError * _Nonnull error) {
        NSLog(@"EyuSDKBridge - Init Fail! - msg:%@", error);
        NSString * callMsg = [SDKBridgeUtil ObjectToJson:error.userInfo];
        self.m_InitResult = @"1!state:fail";
        [SDKBridgeUtil SendMsgToUnity:UnitySdkInitFailFunc msg:callMsg];
    }];
}

- (void)login{
    NSLog(@"EyuSDKBridge - Login...");
    [[AboGameSDKApi SDKManager]StartSiginServiceDoneSuccess:^(NSDictionary * _Nonnull successBack){
        
        //能进来这里 必定是调用了登录方法 登陆成功的
        
        NSLog(@"EyuSDKBridge - Login Success! - msg:%@", successBack);
        NSString * gameToken = [successBack valueForKey:@"gameToken"];
        NSString * timeStamp = [successBack valueForKey:@"timeStamp"];
        NSString * uid = [[[successBack valueForKey:@"user"]valueForKey:@"uid"]description];
        if (gameToken && timeStamp && uid) {
            [EyuHeader Instance].m_UserId = uid;
            NSLog(@"--->>> login success - userId:%@", [EyuHeader Instance].m_UserId);
            self.m_IsLoginSucceed = YES;
            NSNumber * isLogin = [[successBack valueForKey:@"user"]valueForKey:@"is_login"];
            if (isLogin.intValue == 0){ // 0 -> 注册; 1 -> 登陆
                [self eventReport:EYU_CUSTOM_CREATE_ROLE dict:@{}];
            }
            NSString * output = [NSString stringWithFormat:@"1!{\"state\":\"success\", \"gameToken\":%@, \"uid\":%@}", gameToken, uid];
            self.m_LoginResult = output;
            [SDKBridgeUtil SendMsgToUnity:UnitySdkLoginSuccessFunc msg:@"1"];
            [self eventReport:EYU_LOGIN dict:@{}];
        }else{
            // 登陆异常
            //避免显示太长
            if (gameToken.length>10) {
                gameToken=[gameToken substringToIndex:5];
            }
            NSLog(@"登录成功但是返回数据异常？:%@",gameToken);
            NSString * output = [NSString stringWithFormat:@"0!{\"state\":\"error\", \"gameToken\":%@}", gameToken];
            self.m_LoginResult = output;
            [SDKBridgeUtil SendMsgToUnity:UnitySdkLoginFailFunc msg:[@"0!" stringByAppendingString:gameToken]];
        }
    } eyuFail:^(NSError * _Nonnull error){
        NSLog(@"EyuSDKBridge - Login Fail! - msg:%@", error);
        NSString * callMsg = [SDKBridgeUtil ObjectToJson:error.userInfo];
        self.m_LoginResult = @"0!state:error";
        [SDKBridgeUtil SendMsgToUnity:UnitySdkLoginFailFunc msg:callMsg];
    }];
}

- (BOOL)isAdLoad:(int)type{
    if (!self.m_IsLoginSucceed) return false;
    return [EyuAdBridge IsAdLoad:type];
}

- (BOOL)showAd:(int)type{
    if (!self.m_IsLoginSucceed) return false;
    return [EyuAdBridge ShowAd:type];
}

- (void)hideAd:(int)type{
    if (!self.m_IsLoginSucceed) return;
    [EyuAdBridge HideAd:type];
}

- (void)purchase:(NSString *)purchaseData{
    if (!self.m_IsLoginSucceed) return;
    [EyuPurchaseBridge Purchase:purchaseData];
}

- (void)queryProducts:(NSString *)productList type:(int)type{
    if (!self.m_IsLoginSucceed) return;
    [EyuPurchaseBridge QueryProducts:productList type:type];
}
// 事件上报
- (void)eventReport:(NSString *)eventName propertiesJson:(NSString *)propertiesJson{
    if (!self.m_IsLoginSucceed) return;
    [EyuReportBridge eventReport:eventName propertiesJson:propertiesJson];
}

- (void)eventReport:(NSString *)eventName dict:(NSDictionary *)dict{
    [EyuReportBridge eventReport:eventName dict:dict];
}

- (BOOL)getLoginSuccess{
    return self.m_IsLoginSucceed;
}

- (NSString *)getInitResult{
    return self.m_InitResult;
}

- (NSString *)getLoginResult{
    return self.m_LoginResult;
}

- (NSString *)getProtocolUrl{
    return [[AboGameSDKApi SDKManager] GameProtocolUrl];
}

- (NSString *)getPrivacyUrl{
    return [[AboGameSDKApi SDKManager] GameProvacyUrl];
}

- (NSString *)getAdTag{
    return [[AboGameSDKApi SDKManager] GameGetAdtag];
}

- (void)requestFAQ{
    [[AboGameSDKApi SDKManager] GameOpenFAQ];
}

//如果接入个人中心的话
//用户在个人中心切换了账号
-(void)UserSignOtherAccount:(NSNotification*)notification{
    self.m_IsLoginSucceed=YES;
    //与⽤户登录返回的数据内容格式⼀致，示例请查看登录返回示例
    NSDictionary*loginData=notification.userInfo;
    //研发处理切换账号的⽅法
    
}

@end
